package com.duofan.gmall.ware.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.common.exception.NoStockException;
import com.duofan.gmall.common.to.SkuHasStockTo;
import com.duofan.gmall.common.to.mq.OrderTo;
import com.duofan.gmall.common.to.mq.StockDetailTo;
import com.duofan.gmall.common.to.mq.StockLockedTo;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.ware.config.MyRabbitConfig;
import com.duofan.gmall.ware.entity.WareOrderTaskDetailEntity;
import com.duofan.gmall.ware.entity.WareOrderTaskEntity;
import com.duofan.gmall.ware.feign.OrderFeignService;
import com.duofan.gmall.ware.feign.ProductFeignService;
import com.duofan.gmall.ware.service.WareOrderTaskDetailService;
import com.duofan.gmall.ware.service.WareOrderTaskService;
import com.duofan.gmall.ware.vo.OrderItemVo;
import com.duofan.gmall.ware.vo.OrderVo;
import com.duofan.gmall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.ware.dao.WareSkuDao;
import com.duofan.gmall.ware.entity.WareSkuEntity;
import com.duofan.gmall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    OrderFeignService orderFeignService;

    /**
     * 库存自动解锁
     * 1.下单成功,库存锁成功,后续逻辑失败导致订单回滚
     * 2.订单失败,必须解锁
     * 3.库存锁失败无需解锁
     * 4.有订单,订单状态为已取消,需解锁库存
     * 5.解锁库存消息失败,要通知服务器解锁失败
     * @param to
     */
    public void unlockStock(StockLockedTo to)  {
        log.info("接收到消息: \n {}", JSON.toJSONString(to, true));
        StockDetailTo detailTo = to.getDetail();
        Long detailId = detailTo.getId();
        WareOrderTaskDetailEntity detailEntity = wareOrderTaskDetailService.getById(detailId);
        if(detailEntity != null && detailEntity.getLockStatus() == 1) {
            // 有工作单数据说明库存锁定成功
            // 订单状态为取消,解锁库存
            Long taskId = to.getId();
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(taskId);
            String orderSn = taskEntity.getOrderSn();
            // 根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0) {
                OrderVo orderVo = r.getData(new TypeReference<OrderVo>() {});
                // 解锁
                if(orderVo == null || orderVo.getStatus() == 4) {
                    baseMapper.unlockStock(detailTo);
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity();
                    taskDetailEntity.setId(detailId);
                    taskDetailEntity.setLockStatus(2);
                    wareOrderTaskDetailService.updateById(taskDetailEntity);
                }
            } else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 查库存工作单
        WareOrderTaskEntity taskEntity = wareOrderTaskService.getWareOrderTasKByOrderSn(orderSn);
        // 找到所有没有解锁得库存
        List<WareOrderTaskDetailEntity> taskDetailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", taskEntity.getId())
                // 未解锁状态
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity taskDetailEntity : taskDetailEntities) {
            StockDetailTo detailTo = new StockDetailTo();
            BeanUtils.copyProperties(taskDetailEntity, detailTo);
            baseMapper.unlockStock(detailTo);
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        // skuId:
        //wareId:
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId)
                .eq("ware_id", wareId));
        if(count == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // 失败不回滚事务
            try {
                R skuInfo = productFeignService.info(skuId);
                if(skuInfo.getCode() == 0) {
                    Map<String, Object> data = (Map<String, Object>)skuInfo.get("skuInfo");
                    wareSkuEntity.setSkuName((String)data.get("skuName"));
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            this.baseMapper.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockTo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> vos = skuIds.stream().map(skuId -> {
            SkuHasStockTo vo = new SkuHasStockTo();
            // 多个仓库总库存
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return vos;
    }

    // 默认运行时异常都会回滚
    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public void orderLockStock(WareSkuLockVo vo) throws NoStockException {
        // 保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);

        // 1 按照下单的收获地址,锁定一个就近仓库(忽略)
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHashStock> stocks = locks.stream().map(item -> {
            SkuWareHashStock stock = new SkuWareHashStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());
        for (SkuWareHashStock stock : stocks) {
            boolean skuLock = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if(CollectionUtils.isEmpty(wareIds)) {
                throw new NoStockException("商品Id: " + skuId + "库存不足");
            }
            for (Long wareId : wareIds) {
                // 成功返回1,否则0
                Integer count = baseMapper.lockSkuStock(skuId, wareId, stock.getNum());
                if(count == 1) {
                    skuLock = true;
                    // 锁定成功发消息
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(
                            null, skuId, null, stock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);

                    // 工作单记录发送给mq
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, detailTo);
                    lockedTo.setDetail(detailTo);
                    rabbitTemplate.convertAndSend(MyRabbitConfig.STOCK_EVENT_EXCHANGE, MyRabbitConfig.STOCK_LOCKED_ROUTING_KEY, lockedTo);

                    break;
                }
            }
            if(!skuLock) {
                throw new NoStockException("商品Id: " + skuId + "库存不足");
            }
        }
    }

    @Data
    class SkuWareHashStock {
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }

}